<?php
namespace app\admin\controller;
use think\Request;
use app\common\model\ConfigModel;
use app\common\controller\Backend;
use app\common\model\CategoryModel;

class Category extends Backend
{
	//分类列表
	public function index(Request $request = null)
	{
    //获取全部分类
    $CategoryModel = new CategoryModel();
    $categoryList = $CategoryModel->getAllCategory();

  	return view("index",[
  	'categoryList' => $categoryList,
  	]);
	}

	//分类创建
	public function create(Request $request = null){
    if($request->isPost()){
      $post = $request->post();
      $CategoryModel = new CategoryModel();
      $result = $CategoryModel->allowField(true)->validate(true)->save($post);
      
      if(false === $result){
        // 验证失败 输出错误信息
        $this->error($CategoryModel->getError());
      }else{
        $this->success("成功！");
      }
    }else{
			$parentId = $request->param("parent_id");

	    //获取全部分类
	    $CategoryModel = new CategoryModel();
	    $categoryList = $CategoryModel->getAllCategory();
 
			return view("create",[
				'categoryList' => $categoryList,
        'parentId' => $parentId
			]);
    }
	}


  //更新分类
  public function update(Request $request = null){
    if($request->isPost()){
      $post = $request->post();
      $CategoryModel = new CategoryModel();

      $result = $CategoryModel->allowField(true)->validate(true)->save($post,['id'=>$post['id']]);

      if(false === $result){
          // 验证失败 输出错误信息
          $this->error($CategoryModel->getError());
      }else{

        $this->success("成功！");
      }
    }else{
      $id = Request::instance()->param('id/d',0);
      
      //获取全部分类
      $CategoryModel = new CategoryModel();
      $categoryModel = $CategoryModel->getCategoryById($id);
      $categoryList = $CategoryModel->getAllCategory();

      return view("update",['categoryModel'=> $categoryModel,'categoryList'=>$categoryList]);
    }
  }

  /*删除*/
  public function deleteall(Request $request = null){
    $CategoryModel = new CategoryModel();
    $id = $request->post("id");
    if($CategoryModel->isChildren($id)){
      return json(['status'=>400,'msg'=>'请先去删除子分类！']);
    }
    if($CategoryModel->deleteAll($id) > 0){
      return json(['status'=>200,'msg'=>'成功']);
    }else{
      return json(['status'=>400,'msg'=>'失败']);
    }
  }


}